﻿using System.Collections.Generic;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using System.Collections.Concurrent;

namespace System {
    /// <summary>
    /// https://api.weixin.qq.com
    /// </summary>
    public class WeiXinHelper {
        /// <summary>
        /// 获取session_key
        /// authorization_code
        /// https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/login/auth.code2Session.html
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public static SessionBag GetOpenid(string code) {
            string url = $"https://api.weixin.qq.com/sns/jscode2session?appid={AppConfig.APPID}&secret={AppConfig.AppSecret}&js_code={code}&grant_type=authorization_code";
            var data = Utils.HttpGet(url);
            var sessionBag = data.ToObject<SessionBag>();
            return sessionBag;
        }
        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="paramData"></param>
        /// <returns></returns>
        public static string sendMessage(IDictionary<string,string> paramData) {
            string url = $"https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token="+getToken();
            Utils.HttpPost(url,paramData);
            return "";
        }
        /// <summary>
        /// 获取 Token
        /// </summary>
        /// <returns></returns>
        public static string getToken() {
            string url = $"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={AppConfig.APPID}&secret={AppConfig.AppSecret}";
            var data = Utils.HttpGet(url);
            JObject sk = JObject.Parse(data);
            return sk["access_token"].ToString();
        }
    }
}
